import React, { useEffect, useState } from 'react'
import {
  Button,
  message,
  Modal,
  Space,
  Table,
  Checkbox,
  Empty,
  notification,
  Spin,
  Form,
  Row,
  Col,
  Input,
  Select,
  DatePicker,
  Typography,
  InputNumber,
} from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import * as mathjs from 'mathjs'
import {
  queryIntentOrderList,
  exportIntentOrder,
  getListIntentOrderSpuByCodes,
  intentOrderCancelIntentOrder,
  copyIntentOrderIntentOrder,
  rejectIntentOrderIntentOrder,
  getByIntentOrderCode,
  splitIntentOrder,
} from '@/api/purchase'
import { intentOrderReplyIntentOrder, generatePurchaseOrder, intentOrderImportReply } from '@/api/purchase'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns, useInnerColumns, useViewSkuColumns, useReplyColumns } from './columns'
import { IntentOrderDetailVO, IntentOrderVO as ITableData } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import CustomTable from '@/components/CustomTable'
import { applicationTypeEnum, IMPORT_FILE_ENUM, OperationLogType } from '@/constant'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import { UploadOutlined, ExclamationCircleOutlined, PlusOutlined, ImportOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { getProductClassConfigByType, getSpuOptions, importIntentOrderExcel } from '@/api/goods'
import { INTENT_ORDER_TYPE_OPTIONS, PURCHASEWAY_OPTIONS } from '@/constant/purchase'
import useSearchUser from '@/hooks/useSearchUser'
import { useReplyForm } from './useForm'
import { exportNotification, getRecentThreeMonths } from '@/utils/util'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import './index.less'
import ImportFileModal from '@/components/ImportFileModal'
import {
  intentOrderCountTodo,
  updateIntentOrderBoxNum,
  updateIntentOrderDetail,
  updateIntentOrderTime,
  updateReleaseSeasonDate,
} from '@/api/reorder'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useViewLogs from '@/hooks/useViewLogs'
import LogsDrawer from '@/components/LogsDrawer'
import useCachePage from '@/hooks/useCachePage'
import { validatePackageNum } from '@/utils/validator'
import { getDetailInfos } from '@/api/supplier'
import useModal from '@/hooks/useModal'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const [FormReply] = useForm()
  const [FormReturnBack] = useForm()
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [statusFlag, setstatusFlag] = useState(false)
  const [isselectDiff, setisselectDiff] = useState(false)
  const [isModalShow, setisModalShow] = useState(false)
  const [DisabledPrice, setDisabledPrice] = useState(false)
  const [quotationOrderCode, setquotationOrderCode] = useState<string | null>(null)
  const [isSaveLoading, setisSaveLoading] = useState(false)
  const [isReturnModalShow, setisReturnModalShow] = useState<boolean>(false)
  const [viewList, setviewList] = useState<any[]>([])
  const [formSkuSearch] = useForm()
  const [selectSpuInfo, setSelectSpuInfo] = useState<Record<string, any>>({})
  const [skuCodesOption, setskuCodesOption] = useState<IOptionItem[]>([])
  const [tempCode, setTempcode] = useState<
    IMPORT_FILE_ENUM.IMPTINTENTDER_IMPORT | IMPORT_FILE_ENUM.IMPTINTREPLY_IMPORT
  >(IMPORT_FILE_ENUM.IMPTINTENTDER_IMPORT)
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier('supplierId')
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  // 日志
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'intentOrderCode',
    OperationLogType.INTENT_ORDER,
  )
  const [orderNum, setorderNum] = useState<{ waitConfirmOrderNum: number; waitReplyOrderNum: number }>({
    waitConfirmOrderNum: 0,
    waitReplyOrderNum: 0,
  })
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormUpload] = useForm()
  const [FormSend] = useForm()
  const [FormRs] = useForm()
  const [FormInOut] = useForm()
  const [replyModalShow, setreplyModalShow] = useState(false)
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [runModalShow, setrunModalShow] = useState<boolean>(false)
  const [inoutModalShow, setinoutModalShow] = useState<boolean>(false)
  const [rsModalShow, setrsModalShow] = useState<boolean>(false)
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [isCommonPrice, setisCommonPrice] = useState<boolean>(true)
  const [expand, setexpand] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const [CurrentInfo, setCurrentInfo] = useState<Record<string, any>>({})
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const [expandedRowKeys, setexpandedRowKeys] = useState<React.Key[]>([])
  const [spinning, setspinning] = useState<boolean>(false)
  const defaultDateRange = getRecentThreeMonths()
  const { setCachePage, getCachePage } = useCachePage()
  const [colorOptions, setcolorOptions] = useState<IOptionItem[]>([])
  const [hasFinished, sethasFinished] = useState<boolean>(false)
  const [colorCodes, setcolorCodes] = useState<string[]>([])
  const colorModal = useModal({
    onSuccess: (res) => {
      message.success('分色拆单成功，新意向单号：' + res?.data)
      sethasFinished(true)
    },
    onReload: () => {
      reloadPage()
    },
  })
  useEffect(() => {
    if (colorCodes && colorCodes.length > 0 && hasFinished) {
      console.log(viewList, 'viewList')
      const newviewList = viewList.filter((item) => !colorCodes.includes(item?.productSimpleVO?.colorCode))
      setviewList([...newviewList])
    }
  }, [colorCodes, hasFinished])
  const { tableProps, params, search } = useGetTableData<ITableData>(queryIntentOrderList, {
    form: form,
    defaultFieldsParams: {
      startTime: defaultDateRange,
      selectDiff: isselectDiff ? 1 : 0,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  const { UserOptions, handleSearchUser, setUserOptions } = useSearchUser()
  useEffect(() => {
    getToDoList()
    getProductClassConfig()
    handleCacheData()
  }, [])
  useEffect(() => {
    const data = tableProps?.dataSource?.map((item) => item?.intentOrderCode)
    if (expand) {
      setexpandedRowKeys(data)
    } else {
      setexpandedRowKeys([])
    }
  }, [tableProps.dataSource, expand])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      const paramsData = {
        ...params,
        startTime: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        intentOrderCodes: cacheData?.intentOrderCodes != null ? cacheData.intentOrderCodes : null,
      }
      onSearch(
        {
          ...paramsData,
        },
        { selectDiff: isselectDiff ? 1 : 0 },
      )
      setCachePage({
        ...paramsData,
        selectDiff: isselectDiff ? 1 : 0,
      })
    } else {
      form.setFieldsValue({
        ...cacheData,
        startTime:
          cacheData.startTime && cacheData.endTime ? [dayjs(cacheData.startTime), dayjs(cacheData.endTime)] : null,
        intentOrderCodes: cacheData?.intentOrderCodes != null ? cacheData.intentOrderCodes : null,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      setUserOptions(cacheData?.UserOptions || [])
      setSkuOptions(cacheData?.SkuOptions || [])
      const { SpuOptions, UserOptions, SkuOptions, SupplierOption, selectDiff, ...newParams } = cacheData
      setisselectDiff(!!selectDiff)
      onSearch(
        {
          ...newParams,
        },
        { selectDiff: cacheData?.selectDiff },
      )
    }
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedRowInfos(info)
  }
  const getToDoList = async () => {
    const res = await intentOrderCountTodo<{ waitConfirmOrderNum: number; waitReplyOrderNum: number }>()
    if (res.code === 200 && res?.data != null) {
      setorderNum(res?.data)
    }
  }
  const expandedRowRender = (rows: ITableData) => {
    return (
      <Table
        rowKey={(rows) => rows.id}
        columns={useInnerColumns({ onEdit, canEditOperation: buttonCodeList.includes('editOperation') })}
        dataSource={rows?.detailVOS || []}
        pagination={false}
        scroll={{
          x: 'max-content',
        }}
        rowHoverable={false}
        rowClassName={(_, index) => {
          return index % 2 === 0 ? '' : 'zebra-row-odd'
        }}
      />
    )
  }
  const onEdit = (info: ITableData) => {
    setCurrentInfo(info)
    const viewList =
      tableProps.dataSource?.find((item) => item.intentOrderCode === info.intentOrderCode)?.detailVOS || []
    setviewList(viewList)
    getSelectOptions(info.spuCode)
    setisModalShow(true)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onReply = async (info: ITableData, sendReq: boolean) => {
    setCurrentInfo(info)
    if (sendReq) {
      const intentDetailQuotationVOS = await getQuotationOrder(
        info?.intentSupplierId,
        info?.detailVOS?.[0]?.spuCode,
        info?.orderType,
        info.intentOrderCode,
      )
      info?.detailVOS?.forEach((item) => {
        intentDetailQuotationVOS?.forEach((it) => {
          if (item?.productSimpleVO?.colorDetailName === it.colorDetailName) {
            item.recoverCostPrice = it.negotiatePrice
          }
        })
      })
      setviewList(info?.detailVOS || [])
      const colorOptions = Array.from(
        new Map(
          info?.detailVOS?.map((item: any) => {
            const colorCode = item?.productSimpleVO?.colorCode
            const colorDetailName = item?.productSimpleVO?.colorDetailName
            return [
              colorCode,
              {
                label: colorDetailName,
                value: colorCode,
              },
            ]
          }) || [],
        ).values(),
      )
      setcolorOptions(colorOptions)
    }
    const res = await getDetailInfos<ITableData>({ id: info?.intentSupplierId })
    if (res.code == 200) {
      setSupplierOption([{ label: res?.data?.supplierName, value: res?.data?.supplierId }])
      setreplyModalShow(true)
      FormReply.setFieldsValue({
        replySupplierId: res?.data?.supplierId,
        requiredArrivalTime: info.planDate ? dayjs(info.planDate) : null,
      })
      setDisabledPrice(
        (info.orderType === 0 && res?.data?.firstOrderMustQuotation === 1) ||
          (info.orderType === 1 && res?.data?.reorderMustQuotation === 1),
      )
    }
  }
  const getQuotationOrder = async (
    supplierId?: number,
    spuCode?: string,
    orderType?: number,
    intentOrderCode?: string,
  ) => {
    const res = await getByIntentOrderCode<{
      intentDetailQuotationVOS: any[] | null
      quotationOrderCode: string | null
    }>({
      supplierId,
      spuCode,
      orderType,
      intentOrderCode,
    })
    setquotationOrderCode(res?.data?.quotationOrderCode || null)
    return res?.data?.intentDetailQuotationVOS || null
  }
  const onEditTime = (info: ITableData) => {
    setCurrentInfo(info)
    FormSend.setFieldValue('planDate', info.planDate ? dayjs(info.planDate) : dayjs())
    setrunModalShow(true)
  }
  const onEditInOut = (info: ITableData & { inorout: 1 | 2 }) => {
    setCurrentInfo(info)
    info.inorout == 1
      ? FormInOut.setFieldValue('num', info.inPackageNum || null)
      : FormInOut.setFieldValue('num', info.outPackageNum || null)
    setinoutModalShow(true)
  }
  const onEditRsTime = (info: ITableData) => {
    setCurrentInfo(info)
    FormRs.setFieldValue('releaseSeasonDate', info.releaseSeasonDate ? dayjs(info.releaseSeasonDate) : dayjs())
    setrsModalShow(true)
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const onReplyConfirm = async (vals: any) => {
    if (!statusFlag && viewList?.some((item) => !item.recoverCostPrice)) {
      message.warning('供应链回复价格不能为空，请检查报价单是否已确认！')
      return
    }
    const res = await intentOrderReplyIntentOrder({
      intentOrderCode: CurrentInfo.intentOrderCode,
      replySupplierId: vals.replySupplierId,
      replyDeliveryTime: vals.replyDeliveryTime && dayjs(vals.replyDeliveryTime).format('YYYY-MM-DD'),
      requiredArrivalTime: vals.requiredArrivalTime && dayjs(vals.requiredArrivalTime).format('YYYY-MM-DD'),
      replyRemark: vals.replyRemark,
      detailDTOS: !statusFlag ? viewList : [],
      spuCode: CurrentInfo?.detailVOS?.[0]?.spuCode,
      replyStatus: !statusFlag ? 0 : 1,
      quotationOrderCode: !statusFlag ? quotationOrderCode : CurrentInfo?.quotationOrderCode,
    })
    if (res.code === 200) {
      onModalCancel()
      reloadPage()
      message.success('操作成功')
    }
  }
  const onSearch = (vals: any, extraParams: Record<string, any> = { selectDiff: 0 }) => {
    setselectedRowKeys([])
    setselectedRowInfos([])
    const paramsData = {
      ...vals,
      ...extraParams,
      startTime: Array.isArray(vals?.startTime)
        ? dayjs(vals.startTime[0]).format('YYYY-MM-DD HH:mm:ss')
        : vals?.startTime
        ? vals?.startTime
        : null,
      endTime: Array.isArray(vals?.startTime)
        ? dayjs(vals.startTime[1]).format('YYYY-MM-DD HH:mm:ss')
        : vals?.endTime
        ? vals?.endTime
        : null,
      intentOrderCodes: vals?.intentOrderCodes?.length > 0 ? vals.intentOrderCodes : null,
    }
    search({
      ...paramsData,
    })
    setCachePage({
      ...paramsData,
      SpuOptions,
      UserOptions,
      SkuOptions,
      SupplierOption,
    })
    getToDoList()
  }
  const onModalCancel = () => {
    setisModalShow(false)
    setCurrentInfo({})
    setviewList([])
    setreplyModalShow(false)
    setrunModalShow(false)
    setinoutModalShow(false)
    setrsModalShow(false)
    setisReturnModalShow(false)
    FormReply.resetFields()
    FormSend.resetFields()
    FormRs.resetFields()
    FormInOut.resetFields()
    FormReturnBack.resetFields()
    setcolorCodes([])
    setcolorOptions([])
    sethasFinished(false)
  }
  const saveProduct = async () => {
    setisSaveLoading(true)
    const res = await updateIntentOrderDetail({
      intentOrderCode: CurrentInfo.intentOrderCode,
      spuDetailDTOS: viewList?.map((item) => {
        return {
          ...item,
          intentOrderDetailId: item?.id,
        }
      }),
    }).finally(() => setisSaveLoading(false))
    if (res.code === 200) {
      onModalCancel()
      reloadPage()
      message.success('操作成功')
    }
  }
  const handleAddSpu = async () => {
    if (!formSkuSearch.getFieldValue('skuCode')) {
      message.warning('SKU商品不能为空')
      return
    }
    const demandCostPrice = isCommonPrice
      ? viewList[0]?.demandCostPrice || 0
      : viewList?.find((item) => item?.productSimpleVO?.colorDetailName == selectSpuInfo?.colorDetailName)
          ?.demandCostPrice || 0
    setviewList([
      ...viewList,
      {
        spuCode: CurrentInfo?.productSimpleVO?.spuCode,
        skuCode: selectSpuInfo?.skuCode,
        lastPurchasePrice: selectSpuInfo?.lastPurchasePrice,
        tagPrice: CurrentInfo?.tagPrice,
        classConfigId: CurrentInfo?.classConfigId,
        productSimpleVO: selectSpuInfo,
        demandCostPrice,
      },
    ])
    formSkuSearch.setFieldValue('skuCode', null)
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    let res: any
    if (tempCode == IMPORT_FILE_ENUM.IMPTINTENTDER_IMPORT) {
      res = await importIntentOrderExcel<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      if (res.code === 200) {
        notification.success({
          message: '任务已生成，请前往右上角任务中心中查看',
        })
        reloadPage()
        onUploadFileCancel()
      }
    }
    if (tempCode == IMPORT_FILE_ENUM.IMPTINTREPLY_IMPORT) {
      res = await intentOrderImportReply<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      if (res.code === 200) {
        notification.success({
          message: '操作成功',
        })
        reloadPage()
        onUploadFileCancel()
      }
    }
    if (res.code === 820000) {
      notification.open({
        type: 'warning',
        message: res.msg,
      })
    }
  }
  const handleConfirmCreate = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请勾选需要操作的列表数据！')
      return
    }
    const instance = Modal.confirm({
      title: '提示',
      content: '是否确认生成正式采购单?',
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = await generatePurchaseOrder({
          intentOrderCodes: selectedRowKeys,
        }).finally(() => {
          onModalCancel()
          instance.destroy()
        })
        if (res.code === 200) {
          reloadPage()
          message.success('操作成功')
        }
        if (res.code === 820000) {
          notification.open({
            type: 'warning',
            message: res.msg,
          })
        }
      },
    })
  }
  const handleCopyOrder = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请勾选需要操作的列表数据！')
      return
    }
    const instance = Modal.confirm({
      title: '提示',
      content: '是否确认复制意向采购单吗?',
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = await copyIntentOrderIntentOrder({
          intentOrderCodes: selectedRowKeys,
        }).finally(() => {
          instance.destroy()
          onModalCancel()
        })
        if (res.code === 200) {
          reloadPage()
          message.success('操作成功')
        }
        if (res.code === 820000) {
          notification.open({
            type: 'warning',
            message: res.msg,
          })
        }
      },
    })
  }
  const onDel = (info: ITableData) => {
    const resetList = viewList.filter((item) => item.skuCode != info.skuCode)
    setviewList([...resetList])
  }
  const getSelectOptions = async (spuCode: string) => {
    const res = await getListIntentOrderSpuByCodes<{ skuInfoVOS: any[] }>([spuCode])
    if (res.code === 200 && res.data && res.data.length > 0) {
      const skuCodesOption =
        res?.data[0]?.skuInfoVOS?.map((item) => {
          return {
            ...item,
            label: item.skuCode,
            value: item.skuCode,
          }
        }) || []
      setskuCodesOption(skuCodesOption)
    }
  }
  const onSendOk = async () => {
    const data = await FormSend.validateFields()
    const res = await updateIntentOrderTime({
      intentOrderCode: CurrentInfo.intentOrderCode,
      planDate: dayjs(data.planDate).format('YYYY-MM-DD'),
    })
    if (res.code === 200) {
      onModalCancel()
      reloadPage()
      message.success('操作成功')
    }
  }
  const onSendOkRs = async () => {
    const data = await FormRs.validateFields()
    const res = await updateReleaseSeasonDate({
      intentOrderCode: CurrentInfo.intentOrderCode,
      releaseSeasonDate: dayjs(data.releaseSeasonDate).format('YYYY-MM-DD'),
    })
    if (res.code === 200) {
      onModalCancel()
      reloadPage()
      message.success('操作成功')
    }
  }
  const oninoutOk = async () => {
    const data = await FormInOut.validateFields()
    const paramsData = {} as Record<string, any>
    CurrentInfo.inorout == 1 ? (paramsData.inPackageNum = data.num) : (paramsData.outPackageNum = data.num)
    const res = await updateIntentOrderBoxNum({
      intentOrderCode: CurrentInfo.intentOrderCode,
      ...paramsData,
    })
    if (res.code === 200) {
      onModalCancel()
      reloadPage()
      message.success('操作成功')
    }
  }
  const onDelOrder = async (info: ITableData) => {
    const instance = Modal.confirm({
      title: '提示',
      content: '是否确认取消订单?',
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = await intentOrderCancelIntentOrder({
          intentOrderCode: info?.intentOrderCode,
        }).finally(() => {
          onModalCancel()
          instance.destroy()
        })
        if (res.code === 200) {
          reloadPage()
          message.success('操作成功')
        }
      },
    })
  }
  const onRejectOrder = async (info: ITableData) => {
    setisReturnModalShow(true)
    setCurrentInfo(info)
  }
  const onViewLogs = async (info: ITableData) => {
    viewLogs(info)
  }
  const reloadPage = () => {
    onSearch(
      { ...form.getFieldsValue(), current: params.current, size: params.size },
      { selectDiff: isselectDiff ? 1 : 0 },
    )
  }
  const onReturnBack = async () => {
    const data = await FormReturnBack.validateFields()
    setexportLoading(true)
    const res = await rejectIntentOrderIntentOrder({
      intentOrderCode: CurrentInfo?.intentOrderCode,
      remark: data.remark,
    }).finally(() => {
      onModalCancel()
      setexportLoading(false)
    })
    if (res.code === 200) {
      reloadPage()
      message.success('操作成功')
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
        return (
          <div key={item.purchaseOrderCode}>
            {item.purchaseOrderCode},{item.reason}
          </div>
        )
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const handleReplySupplierChange = async (intentSupplierId: number, items: any) => {
    if (!intentSupplierId) return
    setDisabledPrice(
      (CurrentInfo.orderType === 0 && items?.firstOrderMustQuotation === 1) ||
        (CurrentInfo.orderType === 1 && items?.reorderMustQuotation === 1),
    )
    const intentDetailQuotationVOS = await getQuotationOrder(
      intentSupplierId,
      CurrentInfo?.detailVOS?.[0]?.spuCode,
      CurrentInfo?.orderType,
      CurrentInfo.intentOrderCode,
    )
    viewList?.forEach((item: any) => {
      intentDetailQuotationVOS?.forEach((it) => {
        if (item?.productSimpleVO?.colorDetailName === it.colorDetailName) {
          item.recoverCostPrice = it.negotiatePrice
        }
      })
    })
    setviewList([...viewList])
  }
  return (
    <PageContainer className="reorder_demand_page">
      <div className="waittodo_box">
        <div className="wait_main">
          <div className="wm_item">
            <div className="wm_item_title">待供应链回复</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    statuses: [0],
                  })
                  onSearch(
                    { ...form.getFieldsValue(), current: 1, size: params.size },
                    { selectDiff: isselectDiff ? 1 : 0 },
                  )
                }}
              >
                {orderNum.waitReplyOrderNum || 0}单
              </Typography.Link>
            </div>
          </div>
          <div className="wm_item">
            <div className="wm_item_title">待企划确认</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    statuses: [1],
                  })
                  onSearch(
                    { ...form.getFieldsValue(), current: 1, size: params.size },
                    { selectDiff: isselectDiff ? 1 : 0 },
                  )
                }}
              >
                {orderNum.waitConfirmOrderNum || 0}单
              </Typography.Link>
            </div>
          </div>
        </div>
      </div>
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['purchaseOrderCode'], form)}
        searchConfig={[
          {
            label: '意向采购单号',
            name: 'intentOrderCodes',
            placeholder: '多个单号间需要换行或使用","分隔',
            type: 'Select',
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              tokenSeparators: [',', '，', '\n', '\r', '\r\n'],
              notFoundContent: null,
            },
          },
          {
            label: '意向采购单状态',
            name: 'statuses',
            type: 'Select',
            option: INTENT_ORDER_TYPE_OPTIONS,
            config: {
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
          // {
          //   label: '供应链回复状态',
          //   name: 'replyStatus',
          //   type: 'Select',
          //   option: [
          //     { label: '已回复', value: 0 },
          //     { label: '已驳回', value: 1 },
          //   ],
          //   config: {
          //     showSearch: true,
          //     optionFilterProp: 'label',
          //   },
          // },
          { label: '意向订单时间', name: 'startTime', type: 'RangePicker', config: { showTime: true } },
          {
            label: '年份',
            name: 'year',
            type: 'FixedDatePicker',
            placeholder: '请选择年份',
            config: {
              picker: 'year',
              format: 'YYYY',
              customFormat: 'YYYY',
            },
          },
          {
            name: 'seasonCode',
            label: '订单季节',
            type: 'Select',
            option: DICTDATA.order_season,
            placeholder: '请选择订单季节',
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          {
            name: 'intentSupplierId',
            label: '意向供应商',
            type: 'Select',
            option: SupplierOption,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchSupplier,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: '订单类型',
            name: 'orderType',
            type: 'Select',
            option: [
              { label: '首单', value: 0 },
              { label: '返单', value: 1 },
            ],
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: '供应链跟单',
            name: 'trackOrderPersonWorkId',
            type: 'Select',
            option: UserOptions,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchUser,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              fieldNames: { label: 'label', value: 'workId' },
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
            },
          },
          {
            label: '大类',
            name: 'firstClassConfigId',
            type: 'Select',
            option: classBig,
          },
          {
            label: '采购方式',
            name: 'purchaseType',
            type: 'Select',
            option: PURCHASEWAY_OPTIONS,
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          { label: '正式采购单号', name: 'purchaseOrderCode', type: 'Input' },
          {
            label: '异常标签',
            name: 'tags',
            type: 'Select',
            option: [
              { label: '企划驳回', value: 1 },
              { label: '供应链驳回', value: 3 },
              { label: '交期延迟', value: 4 },
              { label: '交期提前', value: 5 },
              { label: '价格上浮', value: 6 },
              { label: '供应商差异', value: 7 },
            ],
            config: {
              optionRender: (option: any) => {
                return <div>{option?.data?.label}</div>
              },
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
        ]}
        onFinish={onSearch}
        onReset={async () => {
          form.resetFields()
          form.setFieldsValue({
            startTime: defaultDateRange,
          })
          const paramsData = Object.fromEntries(
            Object.entries(form.getFieldsValue())?.filter(([_, val]) => val !== undefined),
          )
          setisselectDiff(false)
          onSearch({
            ...paramsData,
            intentOrderCodes: null,
            statuses: null,
            replyStatus: null,
            spuCode: null,
            trackOrderPersonWorkId: null,
            skuCodeList: null,
            firstClassConfigId: null,
            purchaseType: null,
            purchaseOrderCode: null,
            tags: null,
            year: null,
            seasonCode: null,
            intentSupplierId: null,
            orderType: null,
            current: 1,
            size: 10,
          })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="importIntentOrder"
                icon={<ImportOutlined />}
                onClick={() => {
                  setTempcode(IMPORT_FILE_ENUM.IMPTINTENTDER_IMPORT)
                  setisUploadFileShow(true)
                }}
              >
                导入意向采购单
              </PermissionButton>
              <PermissionButton permission="createFormalOrder" onClick={handleConfirmCreate}>
                确认生成正式采购单
              </PermissionButton>
              <PermissionButton
                permission="gylBatchReply"
                onClick={() => {
                  setTempcode(IMPORT_FILE_ENUM.IMPTINTREPLY_IMPORT)
                  setisUploadFileShow(true)
                }}
              >
                供应链批量回复
              </PermissionButton>
              <PermissionButton permission="copyIntentOrder" onClick={handleCopyOrder}>
                复制订单
              </PermissionButton>
              <PermissionButton
                permission="intentorderSplitColor"
                onClick={() => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  if (selectedRowKeys.length > 1) {
                    message.warning('只能勾选一条数据进行分色拆单！')
                    return
                  }
                  if (selectedRowKeys.length === 1) {
                    const info = selectedRowInfos[0]
                    const colorOptions = Array.from(
                      new Map(
                        info?.detailVOS?.map((item: any) => {
                          const colorCode = item?.productSimpleVO?.colorCode
                          const colorDetailName = item?.productSimpleVO?.colorDetailName
                          return [
                            colorCode,
                            {
                              label: colorDetailName,
                              value: colorCode,
                            },
                          ]
                        }) || [],
                      ).values(),
                    )
                    setcolorOptions(colorOptions)
                    colorModal.openModal(info)
                  }
                }}
                icon={<PlusOutlined />}
              >
                分色拆单
              </PermissionButton>
              <Checkbox
                onChange={(event: any) => {
                  setexpand(event.target.checked)
                }}
              >
                展开商品明细
              </Checkbox>
              <Checkbox
                checked={isselectDiff}
                onChange={(event) => {
                  setisselectDiff(event.target.checked)
                  onSearch(
                    { ...form.getFieldsValue(), current: 1, size: params.size },
                    {
                      selectDiff: event.target.checked ? 1 : 0,
                    },
                  )
                }}
              >
                只看供应链回复有差异的
              </Checkbox>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="exportIntentOrder"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectedRowKeys.length > 0) {
                    paramsData.intentOrderCodes = selectedRowKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await exportIntentOrder(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectedRowKeys([])
                      setselectedRowInfos([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                loading={exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        className="small_sise_customtable"
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useIndexColumns({
          navigate,
          onReply,
          onEditTime,
          onEditRsTime,
          onEditInOut,
          onDelOrder,
          onViewLogs,
          onRejectOrder,
          canEditPlanDate: buttonCodeList.includes('editPlanDate'),
          canEditInOrOut: buttonCodeList.includes('intentOrderInOrOut'),
          setstatusFlag,
        })}
        {...tableProps}
        expandable={{
          expandedRowKeys,
          expandedRowRender,
          onExpandedRowsChange: (keys: React.Key[]) => {
            setexpandedRowKeys(keys)
          },
        }}
        rowKey={(rows) => rows.intentOrderCode}
        tableRowGray={(record) => (record.qualityStatus && record.qualityStatus == 4 ? 'table-row-gray' : '')}
        isScrollY
        extraHeight={64}
      />
      <Modal
        title={statusFlag ? '供应链驳回' : '供应链回复'}
        width={statusFlag ? 600 : 1000}
        open={replyModalShow}
        maskClosable
        onCancel={onModalCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onModalCancel}>取消</Button>
              <Button type="primary" onClick={() => FormReply.validateFields().then(onReplyConfirm)}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        {!statusFlag ? (
          <PermissionButton
            style={{ marginBottom: 6 }}
            permission="intentorderSplitColor"
            onClick={() => {
              const detailVOS = CurrentInfo?.detailVOS?.filter(
                (item: any) => !colorCodes.includes(item?.productSimpleVO?.colorCode),
              )
              const colorOptions = Array.from(
                new Map(
                  detailVOS?.map((item: any) => {
                    const colorCode = item?.productSimpleVO?.colorCode
                    const colorDetailName = item?.productSimpleVO?.colorDetailName
                    return [
                      colorCode,
                      {
                        label: colorDetailName,
                        value: colorCode,
                      },
                    ]
                  }) || [],
                ).values(),
              )
              setcolorOptions(colorOptions as IOptionItem[])
              colorModal.openModal(CurrentInfo)
            }}
            icon={<PlusOutlined />}
          >
            分色拆单
          </PermissionButton>
        ) : null}
        <EditFormVertical
          className="demand_width_limit_box"
          editConfig={useReplyForm({
            SupplierOption,
            handleSearchSupplier,
            FormReply,
            statusFlag: !statusFlag,
            handleReplySupplierChange,
            colorOptions,
          })}
          form={FormReply}
          initialValues={{ replyStatus: 0 }}
        >
          {!statusFlag ? (
            <div className="header_table_style small_sise_customtable">
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                <div>【关联报价单号:{quotationOrderCode || '-'}】</div>
                <Checkbox checked={isCommonPrice} onChange={(event) => setisCommonPrice(event.target.checked)}>
                  单价按款式统一
                </Checkbox>
              </div>
              <Table
                bordered
                pagination={false}
                scroll={{
                  y: 300,
                }}
                columns={useReplyColumns({
                  viewList,
                  setviewList,
                  isCommonPrice,
                  DisabledPrice,
                })}
                dataSource={viewList}
                rowKey={(rows) => rows.skuCode}
                rowHoverable={false}
                rowClassName={(_, index) => {
                  return index % 2 === 0 ? '' : 'zebra-row-odd'
                }}
                summary={
                  viewList && viewList.length > 0
                    ? (tableData) => (
                        <Table.Summary>
                          <Table.Summary.Row>
                            <Table.Summary.Cell index={0} align="center">
                              合计
                            </Table.Summary.Cell>
                            <Table.Summary.Cell index={1} colSpan={5}></Table.Summary.Cell>
                            <Table.Summary.Cell index={2} align="center">
                              {tableData?.reduce(
                                (pre, item) =>
                                  mathjs.format(
                                    mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.orderQty || 0)),
                                    {
                                      notation: 'fixed',
                                      precision: 0,
                                    },
                                  ),
                                0,
                              )}
                            </Table.Summary.Cell>
                            <Table.Summary.Cell index={3} colSpan={3}></Table.Summary.Cell>
                            <Table.Summary.Cell index={5} colSpan={1}></Table.Summary.Cell>
                          </Table.Summary.Row>
                        </Table.Summary>
                      )
                    : undefined
                }
              ></Table>
            </div>
          ) : null}
        </EditFormVertical>
      </Modal>

      <Modal
        width={2000}
        title="编辑意向采购商品"
        maskClosable
        open={isModalShow}
        onCancel={onModalCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onModalCancel}>取消</Button>
              <Button type="primary" onClick={() => saveProduct()} loading={isSaveLoading}>
                确认修改
              </Button>
            </Space>
          </div>
        }
      >
        {CurrentInfo?.status == 0 && (
          <div className="search_header_wrap">
            <Form form={formSkuSearch} className="sep_forminline_label add_searchform_inline_box" layout="inline">
              <Row gutter={[10, 10]}>
                <Col {...{ xs: 24, sm: 24, md: 12, lg: 8, xl: 6, xxl: 6 }}>
                  <Form.Item label="SKU商品" name="skuCode">
                    <Select
                      notFoundContent={<Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                      showSearch
                      options={skuCodesOption.filter((it) => !viewList.map((item) => item.skuCode)?.includes(it.value))}
                      suffixIcon={null}
                      labelInValue
                      placeholder="请输入商品条码"
                      onChange={(_, info: any) => {
                        setSelectSpuInfo({
                          ...info,
                          size: info?.sizeInfo,
                          spuCode: CurrentInfo?.productSimpleVO?.spuCode,
                          designCode: CurrentInfo?.productSimpleVO?.designCode,
                          spuName: CurrentInfo?.productSimpleVO?.spuName,
                          className: CurrentInfo?.productSimpleVO?.className,
                        })
                      }}
                    ></Select>
                  </Form.Item>
                </Col>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => handleAddSpu()}>
                  添加条码
                </Button>
              </Row>
            </Form>
          </div>
        )}
        <div className="header_table_style small_sise_customtable">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', marginBottom: 6 }}>
            <Checkbox checked={isCommonPrice} onChange={(event) => setisCommonPrice(event.target.checked)}>
              单价按款式统一
            </Checkbox>
          </div>
          <Table
            bordered
            pagination={false}
            scroll={{
              y: 300,
            }}
            columns={useViewSkuColumns({
              onDel,
              viewList,
              setviewList,
              isCommonPrice,
            })}
            dataSource={viewList}
            rowKey={(rows) => rows.skuCode}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          ></Table>
        </div>
      </Modal>
      <Modal title="意向到仓日期" open={runModalShow} onCancel={onModalCancel} onOk={onSendOk}>
        <Form form={FormSend} layout="vertical">
          <Form.Item
            label="意向到仓日期"
            name="planDate"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择意向到仓日期',
              },
            ]}
          >
            <DatePicker></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
      <Modal title="上市日期" open={rsModalShow} onCancel={onModalCancel} onOk={onSendOkRs}>
        <Form form={FormRs} layout="vertical">
          <Form.Item
            label="上市日期"
            name="releaseSeasonDate"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择上市日期',
              },
            ]}
          >
            <DatePicker></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="驳回原因"
        open={isReturnModalShow}
        onCancel={onModalCancel}
        onOk={onReturnBack}
        confirmLoading={exportLoading}
      >
        <Form form={FormReturnBack} layout="vertical">
          <Form.Item
            label="驳回原因"
            name="remark"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请填写驳回原因',
              },
            ]}
          >
            <Input.TextArea placeholder="请输入驳回原因"></Input.TextArea>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={CurrentInfo.inorout == 1 ? '更新内箱数' : '更新外箱数'}
        open={inoutModalShow}
        onCancel={onModalCancel}
        onOk={oninoutOk}
        confirmLoading={exportLoading}
      >
        <Form form={FormInOut} layout="vertical">
          <Form.Item
            label={CurrentInfo.inorout == 1 ? '内箱数' : '外箱数'}
            name="num"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请填写' + (CurrentInfo.inorout == 1 ? '内箱数' : '外箱数'),
              },
              () => ({
                validator: (_: any, value: number) =>
                  validatePackageNum(
                    _,
                    CurrentInfo.inorout == 1 ? value : CurrentInfo.inPackageNum,
                    CurrentInfo.inorout == 2 ? value : CurrentInfo.outPackageNum,
                  ),
              }),
            ]}
          >
            <InputNumber
              precision={0}
              min={1}
              placeholder={'请输入' + (CurrentInfo.inorout == 1 ? '内箱数' : '外箱数')}
            ></InputNumber>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="分色拆单"
        open={colorModal.open}
        maskClosable
        zIndex={1200}
        onCancel={colorModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={colorModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={colorModal.confirmLoading}
                onClick={() =>
                  colorModal.handleSubmit((vals: any) => {
                    setcolorCodes(vals?.colorCodes || [])
                    return splitIntentOrder({
                      colorCodes: vals.colorCodes,
                      intentOrderCode: colorModal.currentRecord.intentOrderCode,
                    })
                  })
                }
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              label: '款式色',
              name: 'colorCodes',
              type: 'Checkbox',
              option: colorOptions,
              placeholder: '请勾选颜色',
              rules: [
                {
                  required: true,
                  message: '请勾选颜色',
                },
              ],
            },
          ]}
          form={colorModal.form}
        />
      </Modal>
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={tempCode}
      ></ImportFileModal>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
